package com.study.spmongodb.book.wwj.char03;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/24 17:59
 */
public class ThreadJoin {

    public static void main(String[] args) throws InterruptedException {
        final List<Thread> threads = IntStream.range(1, 3)
                .mapToObj(ThreadJoin::create).collect(Collectors.toList());

        //2 启动两个线程
        threads.forEach(Thread::start);

        //3 执行两个线程的join方法
        for (Thread thread : threads) {
            thread.join();
        }
        //4 main循环输出
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " # " + i);
            shortSleep();
        }
    }

    // 构造一个简单的线程，每个线程只是简单的循环输出
    private static Thread create(int seq) {
        return new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " # " + i);

            }
        }, String.valueOf(seq));
    }

    private static void shortSleep() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
